<template>
  <div>
    <el-cascader
      :options="options"
      v-model="selectedTime"
      clearable
      @change="handleTimeChange"
      placeholder="请选择时间"
      :style="{ width: widthStyle + 'px' }"
    ></el-cascader>
  </div>
</template>

<script>
export default {
  props: {
    endHour: Number,
    endMinute: Number,
    defaultSelectedTime: {
      type: Array,
      default: () => [],
    },
    widthStyle: {
      type: [Number, String],
      default: 120,
      required: false,
    },
  },
  data() {
    return {
      selectedTime: [],
      options: [],
    };
  },
  watch: {
    selectedTime() {
      let minutes = this.selectedTime
        ? this.selectedTime[0] * 60 + this.selectedTime[1]
        : "";
      this.$emit("input", minutes);
    },
  },
  created() {
    this.generateTimeOptions();
  },
  methods: {
    generateTimeOptions() {
      this.selectedTime = this.defaultSelectedTime;
      this.options = [];
      const startHour = 0; // 范围开始的小时数
      const endHour = this.endHour; // 范围结束的小时数
      const startMinutes = 1; // 范围开始的分钟数
      const interval = 1; // 小时的间隔
      const minutesInterval = 1; // 分钟的间隔
      for (let hour = startHour; hour <= endHour; hour += interval) {
        const hourValue = hour;
        const hourLabel = `${hourValue}小时`;
        const hourOption = {
          value: hourValue,
          label: hourLabel,
          children: [],
        };
        let endMinute;
        if (hour === this.endHour) {
          // 如果是最后一个小时，设置特定范围的分钟数
          endMinute = this.endMinute; // 设置最后一个小时的结束分钟数
        } else {
          endMinute = 59; // 其他小时的结束分钟数为30
        }
        for (
          let minutes = hour === 0 ? startMinutes : 0;
          minutes <= endMinute;
          minutes += minutesInterval
        ) {
          const minutesValue = minutes;
          const minutesLabel = `${minutesValue}分钟`;
          const minutesOption = {
            value: minutesValue,
            label: minutesLabel,
          };
          hourOption.children.push(minutesOption);
        }
        this.options.push(hourOption);
      }
    },

    handleTimeChange(value) {
      this.$emit("timeChange", value);
    },
  },
};
</script>
